import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//服务器 ： 接收到的数据写入文本文件，给出反馈，代码用线程进行封装，为每一个客户端开启一个线程
public class TCP_Demo3_server_plus {
    static int cnt = 0;
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10002);

        while(true){
            Socket socket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\JavaLearn\\idea\\Code\\JavaSE_Code\\MyNet\\src\\tmp\\copy_plus_" + (cnt++) + ".txt"));
                        String line;
                        while((line = bufferedReader.readLine()) != null){
                            bufferedWriter.write(line);
                            bufferedWriter.newLine();
                            bufferedWriter.flush();
                        }
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        writer.write("Server had gotten the data...");
                        writer.newLine();
                        writer.flush();

                    } catch (IOException e) {
                        throw new RuntimeException(e);

                    }
                }
            }).start();

        }
    }


}
